//
//  simShopVisitScheduleController.m
//  simens
//
//  Created by MICHAEL on 12-8-6.
//  Copyright (c) 2012年 yst. All rights reserved.
//

#import "simShopVisitScheduleController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "simSonVisitCalendarViewController.h"

@interface simShopVisitScheduleController ()<UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate>

@property (nonatomic,strong) UITableView *shopVisitScheduleTableView;

@end

@implementation simShopVisitScheduleController

@synthesize shopVisitScheduleTableView = _shopVisitScheduleTableView;

NSArray* tableViewArray;
NSString* titles;

- (void)viewDidLoad {
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title = titles;
    
    self.shopVisitScheduleTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,
                                                                                self.view.bounds.size.height )
                                                               style:UITableViewStylePlain];
    
    [self.shopVisitScheduleTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.shopVisitScheduleTableView setDelegate:self];
    [self.shopVisitScheduleTableView setDataSource:self];
    
    [self.view addSubview: self.shopVisitScheduleTableView];
    
}

-(void) viewDidAppear:(BOOL)animated{
    [self showMbprogress];
    
    NSString* method;
    
    if ([@"n" isEqualToString: [[NSUserDefaults standardUserDefaults]objectForKey:@"t"] ]) {
        method = @"getTheLevelVisitCustRateByPos";
    } else {
        method = @"getVisitCustRate";
    }
    
    
    NSString *u =[NSString stringWithFormat:@"%@/%@?mobile=%@&pwd=%@&posId=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],method,[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"],[[NSUserDefaults standardUserDefaults]objectForKey:@"posId"]];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"n" forKey:@"t"];
        
    NSURL *url = [NSURL URLWithString: u];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDelegate:self];
    [request start];
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellAccessoryNone;
}

//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableViewArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UIButton class]]|
            [v isKindOfClass:[UIProgressView class]]) {
            [v removeFromSuperview];
        }
    }
    
    NSDictionary* temp = [tableViewArray objectAtIndex:indexPath.row];
    
    
    UILabel* empNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 150, 30)];
    [empNameLabel setBackgroundColor:[UIColor clearColor]];
    [empNameLabel setText: [temp objectForKey:@"empName"]];
    empNameLabel.font=[UIFont systemFontOfSize:16];
    empNameLabel.numberOfLines = 2;
    [cell addSubview:empNameLabel];
    
    UIButton* button = [[UIButton alloc] init];
    button.frame = CGRectMake(20, 10, 150, 30);
    [button setTag: indexPath.row];
    [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:button];
    
    UILabel* visitNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 20, 120, 30)];
    [visitNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitNumLabel setText:[NSString stringWithFormat:@"本周拜访进度：%@/%@", [temp objectForKey:@"visitedNum"], [temp objectForKey:@"visitNum"]]];
    [visitNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitNumLabel];
    
    UIProgressView* progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(150, 10, 120, 30)];
    [progressView setProgressViewStyle:UIProgressViewStyleDefault];

    if ([[temp objectForKey:@"visitNum"] floatValue] == 0.00f) {
        progressView.progress = 0.00f;
    } else {
        progressView.progress = [[temp objectForKey:@"visitedNum"] floatValue] / [[temp objectForKey:@"visitNum"] floatValue];
    }
    
    //progressView.frame = CGRectMake(10, 20, self.frame.size.width-20, 20);
    
    if(progressView.progress<0.6){
        [progressView setProgressTintColor:[UIColor redColor]];
    }else {
        [progressView setProgressTintColor:[UIColor greenColor]];
    }
    
    [cell addSubview:progressView];
    
    UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];
    UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
    [cell setBackgroundView:backImgView];
    
    cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}

-(void)btnPressed:(id)sender{
    NSLog(@"button pressed");
    UIButton* btn = (UIButton*)sender;
    simShopVisitScheduleController* controller = [[simShopVisitScheduleController alloc] init];
    NSDictionary* temp = [tableViewArray objectAtIndex: btn.tag];
    NSString *title=[temp objectForKey:@"empName"];
    [controller setTitles:title];
    // set posId
    [[NSUserDefaults standardUserDefaults] setObject:[temp objectForKey:@"posId"] forKey:@"posId"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"t"];
    
    [self.navigationController pushViewController: controller animated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     NSLog(@"table cell selected");
    NSDictionary* temp = [tableViewArray objectAtIndex:indexPath.row];
    NSString *empid=[[temp objectForKey:@"empId"] stringValue];
    NSString *empname=[temp objectForKey:@"empName"];
    simSonVisitCalendarViewController *sonController=[[simSonVisitCalendarViewController alloc] init];
    [sonController setData:empid empName:empname];
    [self.navigationController pushViewController:sonController animated:YES];

    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"t"];

}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    
    if (!error) {
        NSString *res = [request responseString];NSLog(@"load data is:%@",res);
        NSDictionary* dict = [res objectFromJSONString];
        tableViewArray = [dict objectForKey:@"siemensCustomer"];
        
        if ([tableViewArray count] > 0) {
            NSDictionary* temp = [tableViewArray objectAtIndex: 0];
            if ([temp objectForKey:@"parentPos"] != nil) {
                [[NSUserDefaults standardUserDefaults] setObject:[temp objectForKey:@"parentPos"] forKey:@"posId"];
            }
        }
        
        [self hideMbProgress];
    }
    
    [self.shopVisitScheduleTableView reloadData];
    
}


- (void)requestFailed:(ASIHTTPRequest *)request {
    [self hideMbProgress];
}

-(void) setTitles:(NSString*) t {
    titles = t;
}


@end
